/*
 *  Copyright 2019-2023 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.stock.rest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.stock.domain.TblKline;
import me.zhengjie.stock.domain.TblStockPools;
import me.zhengjie.stock.domain.vo.LongLetStockQueryCriteria;
import me.zhengjie.stock.domain.vo.TblKlineQueryCriteria;
import me.zhengjie.stock.service.TblKlineService;
import me.zhengjie.stock.service.TblStockPoolsService;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dolo
 * @date 2024-05-04
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "交易数据管理")
@RequestMapping("/api/tblKline")
public class TblKlineController {

    private final TblKlineService tblKlineService;

    private final TblStockPoolsService stockPoolsService;

    @Log("交易数据数据")
    @ApiOperation("交易数据数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('tblKline:list')")
    public void exportTblKline(HttpServletResponse response, TblKlineQueryCriteria criteria) throws IOException {
        tblKlineService.download(tblKlineService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询交易数据")
    @ApiOperation("查询交易数据")
    @PreAuthorize("@el.check('tblKline:list')")
    public ResponseEntity<PageResult<TblKline>> queryTblKline(TblKlineQueryCriteria criteria, Page<Object> page) {
        return new ResponseEntity<>(tblKlineService.queryAll(criteria, page), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增交易数据")
    @ApiOperation("新增交易数据")
    @PreAuthorize("@el.check('tblKline:add')")
    public ResponseEntity<Object> createTblKline(@Validated @RequestBody TblKline resources) {
        tblKlineService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改交易数据")
    @ApiOperation("修改交易数据")
    @PreAuthorize("@el.check('tblKline:edit')")
    public ResponseEntity<Object> updateTblKline(@Validated @RequestBody TblKline resources) {
        tblKlineService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除交易数据")
    @ApiOperation("删除交易数据")
    @PreAuthorize("@el.check('tblKline:del')")
    public ResponseEntity<Object> deleteTblKline(@RequestBody List<Integer> ids) {
        tblKlineService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping(value = "/updateLongLetStock")
    @Log("更新大长腿股票池")
    @ApiOperation("更新大长腿股票池")
    public ResponseEntity<Object> updateLongLetStock(@Validated @RequestBody LongLetStockQueryCriteria criteria) {
        stockPoolsService.updateLongLetStock(criteria);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping(value = "/getPoolsInfo")
    @Log("查询大长腿股票池")
    @ApiOperation("查询大长腿股票池")
    public ResponseEntity<Object> getPoolsInfo(TblKlineQueryCriteria criteria) {
        LambdaQueryWrapper<TblStockPools> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(criteria.getCode()), TblStockPools::getCode, criteria.getCode());
        queryWrapper.orderByDesc(TblStockPools::getTradingDate);
        List<TblStockPools> stockPools = stockPoolsService.list(queryWrapper);
        return new ResponseEntity<>(stockPools, HttpStatus.OK);
    }

    @GetMapping(value = "/getPoolsKlineInfo")
    @Log("查询大长腿股票池交易数据")
    @ApiOperation("查询大长腿股票池交易数据")
    public ResponseEntity<Object> getPoolsKlineInfo(TblKlineQueryCriteria criteria) {
        LambdaQueryWrapper<TblKline> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(criteria.getCode()), TblKline::getCode, criteria.getCode());
        queryWrapper.eq(StringUtils.isNotEmpty(criteria.getName()), TblKline::getName, criteria.getName());
        queryWrapper.orderByDesc(TblKline::getTradingDate);
        List<TblKline> stockPools = tblKlineService.list(queryWrapper);
        return new ResponseEntity<>(stockPools, HttpStatus.OK);
    }

    @GetMapping(value = "/getStockKlineData")
    @Log("查询个股K线信息数据")
    @ApiOperation("查询个股K线信息数据")
    public ResponseEntity<Object> getStockKlineData(TblKlineQueryCriteria criteria) {
        LambdaQueryWrapper<TblKline> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TblKline::getCode, criteria.getCode());
        queryWrapper.orderByAsc(TblKline::getTradingDate);
        List<TblKline> klineList = tblKlineService.list(queryWrapper);
        int rows = klineList.size();
        int cols = 6;
        Object[][] twoDArray = new Object[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (j == 0) {
                    twoDArray[i][j] = klineList.get(i).getTradingDate();
                } else if (j == 1) {
                    twoDArray[i][j] = klineList.get(i).getOpeningPrice();
                } else if (j == 2) {
                    twoDArray[i][j] = klineList.get(i).getClosingPrice();
                } else if (j == 3) {
                    twoDArray[i][j] = klineList.get(i).getBottomPrice();
                } else if (j == 4) {
                    twoDArray[i][j] = klineList.get(i).getPeakPrice();
                } else if (j == 5) {
                    twoDArray[i][j] = klineList.get(i).getTradingAmount().divide(new BigDecimal(10000000), 2);
                }
            }
        }
        // 成交量数据
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("klineData", twoDArray);
        return new ResponseEntity<>(returnMap, HttpStatus.OK);
    }

}